package com.baiduspring.dubbo.service.server.sms;

import com.baiduspring.domain.SmsCode;
import com.baiduspring.dubbo.service.mybatis.mapper.SmsCodeMapper;
import com.baiduspring.dubbo.service.sms.ReturnCodeMapping;
import com.baiduspring.dubbo.service.sms.SmsCodeService;
import com.baiduspring.error.BaiduSpringException;
import com.baiduspring.utils.date.DateUtils;
import com.google.common.base.Preconditions;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * 短信相关接口实现
 *
 * @author xiongyan
 */
@Service
@Log4j2
public class SmsCodeServiceImpl implements SmsCodeService {
    @Resource
    private SmsCodeMapper smsCodeMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(String mobile, String code, String retrueCode) {
        Preconditions.checkArgument(!StringUtils.isEmpty(mobile), "手机号码不能为空");
        Preconditions.checkArgument(!StringUtils.isEmpty(code), "验证码不能为空");
        Preconditions.checkArgument(!StringUtils.isEmpty(retrueCode), "返回码不能为空");

        SmsCode smsCode = new SmsCode();
        smsCode.setMobile(Long.valueOf(mobile));
        smsCode.setCode(Integer.valueOf(code));
        smsCode.setReturnCode(retrueCode);

        ReturnCodeMapping mapping = ReturnCodeMapping.getInstance();
        smsCode.setDescribe(mapping.mapping("describe_" + retrueCode));
        smsCode.setSolution(mapping.mapping("solution_" + retrueCode));

        smsCode.setSendTime(System.currentTimeMillis());
        smsCode.setDeadline(DateUtils.add(5));

        try {
            smsCodeMapper.insertSelective(smsCode);
        } catch (BaiduSpringException e) {
            log.error("短信验证码保存错误，原因：", e);
            e.setErrorMsg("短信验证码获取失败");
            throw e;
        } catch (Exception e) {
            log.error("短信验证码保存错误，原因：", e);
            throw e;
        }
    }

    @Override
    public Optional<SmsCode> getByMobile(Long mobile, String code) {
        SmsCode smsCode = smsCodeMapper.selectByMobile(mobile, code, System.currentTimeMillis());
        return Optional.ofNullable(smsCode);
    }
}
